package com.lwg.vhr.service.impl;

import com.lwg.vhr.mapper.HrMapper;
import com.lwg.vhr.mapper.HrRoleMapper;
import com.lwg.vhr.model.Hr;
import com.lwg.vhr.model.Role;
import com.lwg.vhr.service.HrService;
import com.lwg.vhr.utils.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HrServiceImpl implements HrService, UserDetailsService {

    @Autowired
    private HrMapper hrMapper;

    @Autowired
    private HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(username);
        if (hr == null) {
            throw new UsernameNotFoundException("该用户名不存在");
        }
        //登录成功后给用户设置角色
        hr.setRoles(hrMapper.getRolesByHrId(hr.getId()));
        return hr;
    }

    /**
     * @author: lwg
     * @Date: 2021/7/27 23:31
     * @Description: 根据用户id查询角色，用于给authorities提供角色 hr里的getAuthorities方法
     */
    @Override
    public List<Role> getRolesByHrId(Integer id) {
        return hrMapper.getRolesByHrId(id);
    }

    @Override
    public List<Hr> getAllHrs(String keywords) {
        return hrMapper.getAllHrs(HrUtils.getCurrentHr().getId(),keywords);
    }

    @Override
    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    @Override
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        hrRoleMapper.deleteHrRoleByHrid(hrid);
        return hrRoleMapper.addHrRole(hrid,rids);
    }

    @Override
    public int deleteHrById(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }
}